const path = require('path')
const fs = require('fs')
const Router = require('koa-router');
const schedule = require("node-schedule");
const Sequelize = require("sequelize");

//自动扫指定目录下面的文件并且加载
function scanFilesByFolder(dir, cb) {

    let _folder = path.resolve(__dirname, dir);
    try {
        const files = fs.readdirSync(_folder);
        files.forEach((file) => {
            let filename = file.replace('.js', '');

            let oFileCnt = require(_folder + '/' + filename);

            cb && cb(filename, oFileCnt);
        })

    } catch (error) {
        console.log('文件自动加载失败...', error);
    }


}


function initRouter(app) {
    const router = new Router();

    scanFilesByFolder('routes', (filename, routes) => {



        let prefix = filename == 'index' ? '' : `/${filename}`;

        routes = typeof routes === 'function' ? routes(app) : routes;

        Object.keys(routes).forEach(key => {
            let [method, path] = key.split(' ');
            //router[method](prefix + path, routes[key]); 
            router[method](prefix + path, async ctx=>{
                app.ctx = ctx;
                await routes[key](app);
            }); 
            console.log(`路由映射：${method}  ${prefix + path}`)
        })

    })

    return router
}


//初始化控制器
function initController(){
    let controllers = {};

    scanFilesByFolder('controller',(filename,ctrl)=>{
        controllers[filename] = ctrl;
    })

    return controllers;
}


//初始化service
function initService(app){
    let services = {};

    scanFilesByFolder('service',(filename,service)=>{
        services[filename] = service(app);
    })

    return services;
}

//加载定时任务
function initSchedule(){
    scanFilesByFolder('schedule',(filename,scheduleConf)=>{
        schedule.scheduleJob(scheduleConf.interval,scheduleConf.handler)
    })
}

//初始化数据库、中间件。。。
function initConfig(app){
    scanFilesByFolder('config',(filename,config)=>{

        //配置数据库
        if(config.db){
            app.$db = new Sequelize(config.db);
            app.$model = {};
            scanFilesByFolder('model',(modelName,modelConfig)=>{
                app.$model[modelName] = app.$db.define(modelName,modelConfig.schema,modelConfig.options)
            });

            app.$db.sync();
        }

        //初始化中间件
        if(config.middleware){
            config.middleware.forEach(mid=>{

                let midPath = path.resolve(__dirname,'middleware',mid);
                app.$app.use(require(midPath));
            })
        }
    })
}


module.exports = {
    scanFilesByFolder,
    initController,
    initService,
    initSchedule,
    initConfig,
    initRouter
}